Catch Statement
Used to handle RuntimeException errors in a Try block.
Syntax
Catch [ErrorParameter] [As ErrorType]
Part | Description |
ErrorParameter | Optional, used to determine the type of runtime exception. |
ErrorType | Optional, if used, it must be used with ErrorParameter. Used to 'catch' a particular type of runtime error. If used, the Catch statement will handle only that type of runtime error. |
Notes
The Try block is similar to the Exception block. Exceptions that occur within the Try block are caught by the Catch statement. It has the same syntax as the Exception statement. See the RuntimeException statement or the Runtime Errors theme for descriptions of each type of runtime error.
Unlike the Exception block, Try blocks can be nested. If a Try block does not handle an exception or re-raises it, it can be handled by the next outermost Try block, or by the Exception block itself if there are no containing Try blocks.
Local variables that are declared inside a Catch statement exist only within the Catch statement's scope rather than inside the whole method's scope. This means that multiple Catch blocks at the same level can use the same exception variable name.
A Try block can contain its own Finally statement. The code in the Finally statement will execute regardless of whether or not an exception was raised within the Try block.
Example
This example uses the Catch statement to handle an out of range key that is passed to a Dictionary.
SomeValue=myDictionary.Value("badKey")
CatchKeyNotFoundException
MsgBox "The key could not be located."
End Try
See Also
Exception, Try blocks; Finally, Function, Sub statements; RuntimeException error.